#ifndef FILE_ExceptionSafeThread_HPP
#define FILE_ExceptionSafeThread_HPP

#include "System.hpp"
#include "thread.hpp"

#include "NonCopyable.hpp"

/********************************************//**
 * \brief A thread class with delayed launch.
 * 
 * Any exception thrown by your thread will be caught,
 * and written to trace (if has a what()).
 *
 * You may know if the thread terminated normally by
 * Checking the Join() return value (note that a terminated 
 * thread is currently considered as terminated normally).
 ***********************************************/
class se::System::ExceptionSafeThread {
	DISALLOW_COPY_AND_ASSIGN(ExceptionSafeThread);
	public:
		ExceptionSafeThread();
		ExceptionSafeThread(boost::function<void()> t);
		~ExceptionSafeThread();
		virtual void SetFunctor(boost::function<void()> t);
		void SetLogging(bool logAnything, bool logOnCancellation = true);
		virtual void Start();
		bool IsRunning();
		virtual bool Join();
		// Forbidden for now, until a correct behaviour is decided.
		//void Detach();
		void Terminate();
	private:
		void handleExceptions();
		ThreadSignal_t m_terminatedCorrectly;
		bool m_isRunning;
		bool m_freeSelfOnExit;
		bool m_logAnything;
		bool m_logOnCancellation;
		std::thread *m_thread;
		boost::function<void()> m_threadFunctor;
};

#endif //FILE_ExceptionSafeThread_HPP